<template>
  <div class="login_container">
    <el-form class="login_form" ref="loginFormRef" :model="loginFormData" :rules="loginFormValidate" status-icon
      label-width="12px" show-required-asterisk="true" size="large" lable-position="left">
      <h1>Hello</h1>
      <h2>欢迎来到安真通</h2>

      <el-form-item prop="Username" label=" ">
        <el-input type="text" @keyup.enter="handleLogin" placeholder="请输入用户名" :prefix-icon="User"
          v-model="loginFormData.Username"></el-input>
      </el-form-item>
      <el-form-item prop="Password" label=" ">
        <el-input type="password" @keyup.enter="handleLogin" placeholder="请输入密码" :prefix-icon="Lock"
          v-model="loginFormData.Password" show-password></el-input>
      </el-form-item>
      <el-form-item prop="Captcha" label=" ">
        <div class="captcha-container">
          <el-input type="text" @keyup.enter="handleLogin" placeholder="请输入验证码" :prefix-icon="Key"
            v-model="loginFormData.Captcha" style="width: 60%"></el-input>
          <el-button type="primary" :disabled="countdown > 0" @click="getCaptcha" style="width: 38%; margin-left: 2%">
            {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-loading.fullscreen.lock="fullscreenLoading" size="large"
          @click="handleLogin">登录</el-button>
        <p>
          如没有账号，请找管理员申请账号
        </p>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
// @ts-ignore
import { User, Lock, Message, TopLeft, Key } from "@element-plus/icons-vue";
import { ElMessage, ElNotification, FormRules } from "element-plus";
import { reactive, ref, onBeforeUnmount, nextTick } from "vue";
import { reqLogin, PostGetCaptcha } from "@/api/user/index";
import useUserStore from "@/store/modules/user";
import { useRouter, useRoute } from "vue-router";
import { getTime } from "@/utils/time";

const loginFormRef = ref();
const loginFormData = reactive({ Username: "", Password: "", Captcha: "" });
let fullscreenLoading = ref(false);
let $router = useRouter();
let route = useRoute();
let useStore = useUserStore();

const loginFormValidate = reactive<FormRules<typeof loginFormData>>({
  Username: [
    {
      required: true,
      trigger: "blur",
      message: "请输入用户名",
    },
    {
      pattern: /^(?![0-9])[\w\u4e00-\u9fa5]{3,10}$/,
      message: "用户名必须由3-10位字符组成,且不能以数字开头",
      trigger: "blur",
    },
  ],
  Password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      pattern: /^[a-zA-Z/[a-zA-Z0-9_-]{6,18}$/,
      message: "密码必须由6-18位的字母或数字或'_'或'-'组成",
      trigger: "blur",
    },
  ],
});

const handleLogin = async () => {
  fullscreenLoading.value = true;
  
  try {
    // 1. 执行登录请求
    const { data: loginData } = await reqLogin(loginFormData);
    if (loginData.code === 7) {
      throw new Error(loginData.msg);
    }

    // 2. 确保token状态完全同步
    useStore.saveToken(loginData.data.token);
    // 双重保证状态同步
    await nextTick();
    await new Promise(resolve => setTimeout(resolve, 50));
    
    // 3. 执行跳转
    const redirect = route.query.redirect;
    await $router.push(redirect ? decodeURIComponent(redirect as string) : '/home');

    // 3. 后台处理非关键用户信息存储
    setTimeout(() => {
      try {
        localStorage.setItem("authorityId", String(loginData.data.user.authorityId));
        localStorage.setItem("userName", loginData.data.user.nickName);
        localStorage.setItem("userUUID", loginData.data.user.uuid);
        ElMessage.success("登录成功！");
      } catch (e) {
        console.error('后台存储用户信息失败:', e);
      }
    }, 0);

  } catch (error) {
    ElNotification({
      type: "error",
      title: getTime() + "好!",
      message: (error as Error).message,
      showClose: false,
    });
  } finally {
    fullscreenLoading.value = false;
  }
};

const countdown = ref(0)
let timer: any = null

const getCaptchaPost = async () => {
  const { data } = await PostGetCaptcha({
    "username": loginFormData.Username
  })
  if (data.code == 200) {
    fullscreenLoading.value = false
    ElMessage.success(data.msg)
  } else {
    fullscreenLoading.value = false
    ElMessage.error(data.msg)
  }
}

const getCaptcha = () => {
  if (!loginFormData.Username) {
    ElMessage.warning('请输入用户名后再获取验证码')
    return
  }

  fullscreenLoading.value = true
  setTimeout(() => {
    getCaptchaPost()
    countdown.value = 60
    timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  }, 1000)
}

onBeforeUnmount(() => {
  if (timer) clearInterval(timer)
})
</script>

<style scoped lang="scss">
.login_container {
  width: 100%;
  min-height: 100vh;
  padding: 20px;
  background: url("@/assets/images/background.jpg") no-repeat center/cover;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;

  .login_form {
    width: 100%;
    max-width: 340px;
    padding: 20px;
    background-color: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(5px);
    border-radius: 10px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);

    .el-input {
      opacity: 0.9;
    }

    .el-button {
      width: 100%;
      height: 40px;
    }

    .captcha-container {
      display: flex;
      align-items: center;
    }
  }

  h1 {
    color: white;
    font-size: 2rem;
    text-align: center;
    margin-bottom: 10px;
  }

  h2 {
    color: white;
    font-size: 1.2rem;
    text-align: center;
    margin-bottom: 30px;
  }

  p {
    color: #fff;
    width: 100%;
    text-align: center;
    padding: 10px 0;
    font-size: 0.9rem;
    opacity: 0.8;
  }
}

/* 移动端特定样式 */
@media screen and (max-width: 480px) {
  .login_container {
    padding: 10px;

    .login_form {
      padding: 15px;

      h1 {
        font-size: 1.8rem;
      }

      h2 {
        font-size: 1rem;
        margin-bottom: 20px;
      }

      .el-form-item {
        margin-bottom: 20px;
      }

      .captcha-container {
        flex-direction: column;

        .el-input {
          width: 100% !important;
          margin-bottom: 10px;
        }

        .el-button {
          width: 100% !important;
          margin-left: 0 !important;
        }
      }
    }
  }
}
</style>